<script>
import { ref } from 'vue';

export default {
  name: 'user-setting',
};
</script>

<template>
  <div class="settings-container">
    <h2>{{ $t('Setting.user.basicInfo') }}</h2>

    <el-upload
      class="avatar-uploader"
      :show-file-list="false"
      :before-upload="beforeAvatarUpload"
      action="/api/user/upload_avatar"
      :http-request="(options) => handleAvatarUpload(options.file)"
    >
      <div class="preview-container">
        <img v-if="imageUrl" :src="imageUrl" class="avatar" />
        <div v-else class="upload-placeholder">
          <el-icon class="avatar-uploader-icon"><Plus /></el-icon>
          <span class="tip-text">点击上传头像</span>
        </div>
      </div>
    </el-upload>

    <div class="info-row">
      <span>{{ $t('Setting.user.username') }}：</span>
      <span>{{ username }}</span>
      <el-input v-model="username" style="width: 240px" :placeholder="$t('Setting.user.usernamePlaceholder')" />
    </div>

    <div class="info-row">
      <span>{{ $t('Setting.user.userId') }}：</span>
      <span>{{ userId }}</span>
    </div>

    <div class="info-row">
      <span>{{ $t('Setting.user.gender') }}：</span>
      <span>{{ gender }}</span>
      <el-radio-group v-model="gender" style="margin-right: 20px">
        <el-radio label="男">{{ $t('Setting.user.male') }}</el-radio>
      </el-radio-group>
    </div>

    <div class="info-row">
      <span>{{ $t('Setting.user.introduction') }}：</span>
      <span>{{ introduction }}</span>
      <el-input v-model="introduction" style="width: 240px" :placeholder="$t('Setting.user.introductionPlaceholder')" />
    </div>

    <div class="info-row">
      <span>{{ $t('Setting.user.location') }}：</span>
      <span>{{ location }}</span>
      <el-input v-model="location" style="width: 240px" :placeholder="$t('Setting.user.locationPlaceholder')" />
    </div>

    <div class="info-row">
      <span>{{ $t('Setting.user.birthdate') }}：</span>
      <span>{{ birthdate }}</span>
      <div class="demo-date-picker">
        <div class="block">
          <el-date-picker
            v-model="birthdate"
            type="date"
            :placeholder="$t('Setting.user.birthdatePlaceholder')"
            style="width: 240px;"
          />
        </div>
      </div>
    </div>
    <el-button type="primary" plain @click="saveUserInfo" class="save-btn">{{ $t('Setting.user.save') }}</el-button>
  </div>
</template>

<script setup>
import { ElMessage } from 'element-plus'
import { Plus } from '@element-plus/icons-vue'
import {getUserConfig, updateUserConfig, uploadAvatar} from "@/api/api.js";
import {TokenService} from "@/stores/userStore.js";


const username = ref('风雷雷LLL');
const userId = ref('2301_79883587');
const gender = ref('男');
const introduction = ref('大学小白');
const location = ref('哈尔滨市');
const birthdate = ref('1999-09-09');

//input框里输入的内容
// 这些不需要定义，因为每个字段都有自己的输入框

//日期选择器
// birthdate 已经在第一个script中返回，不需要重复定义

// 图片上传不需要在这里定义，已经在第一个script中
// 定义更新方法
const user_id =TokenService.getCurrentUserId()
getUserConfig(user_id).then(res => {
  if (!res.success) {
    console.log(res.message)
  } else {
    console.log(res.message)
    const user_config = res.data;
    username.value = user_config.username;
    userId.value = user_config.user_id;
    gender.value = user_config.gender;
    introduction.value = user_config.bio;
    location.value = user_config.location;
    birthdate.value = user_config.birth_date;
  }
}).catch(err => {

})

const imageUrl = ref('')
const headers = ref({
  Authorization: `Bearer ${localStorage.getItem('token')}`
})

// 文件上传前的校验
const beforeAvatarUpload = (file) => {
  const isValidType = ['image/jpeg', 'image/png', 'image/gif'].includes(file.type)
  const isLt2M = file.size / 1024 / 1024 < 2

  if (!isValidType) {
    console.log('只能上传JPG/PNG/GIF格式的图片!')
    return false
  }
  if (!isLt2M) {
    console.log('图片大小不能超过2MB!')
    return false
  }

  // 生成预览图
  const reader = new FileReader()
  reader.readAsDataURL(file)
  reader.onload = (e) => {
    imageUrl.value = e.target.result
  }

  return true
}

const handleAvatarUpload = async (file) => {
  try {
    const res = await uploadAvatar(file);
    if (res.success) {
      imageUrl.value = res.avatar_url; // 更新头像预览
      console.log('头像上传成功');
    } else {
      console.log(res.message);
    }
  } catch (error) {
    console.log('头像上传失败');
  }
};

const handleAvatarSuccess = (response, file) => {
  imageUrl.value = URL.createObjectURL(file.raw);
  console.log('上传成功');
};

const saveUserInfo = async () => {
  try {
    const res = await updateUserConfig(
      userId.value,
      gender.value,
      introduction.value,
      location.value,
      birthdate.value,
      imageUrl.value // 确保头像 URL 也更新
    );
    if (res.success) {
      console.log('用户信息更新成功');
    } else {
      console.log(res.message);
    }
  } catch (error) {
    console.log('用户信息更新失败');
  }
};

</script>

<style scoped>
@import '/src/css/base.css';
@import "/src/css/setting/user-setting.css";
</style>
